package us.kg.kotoriforest.advance.pool;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * ClassName: us.kg.kotoriforest.advance.pool.HikariTest </br>
 * Description: 测试 Hikari 连接池
 *
 * @author Kotori rotroutine@163.com
 * @since 2024/11/28
 */
public class HikariTest {
    @Test
    public void testHardCodeHikari() {
        // 创建 Hikari 连接池对象
        try (HikariDataSource ds = new HikariDataSource()) {
            // 进行相关配置
            ds.setDriverClassName("com.mysql.cj.jdbc.Driver");
            ds.setJdbcUrl("jdbc:mysql:///JDBC");
            ds.setUsername("root");
            ds.setPassword("");

            ds.setMinimumIdle(10);
            ds.setMaximumPoolSize(20);

            // 获取连接
            try (Connection connection = ds.getConnection()) {
                System.out.println("crud");
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Test
    public void testSoftCodeHikari() {
        Properties properties = new Properties();
        try (InputStream resourceAsStream = HikariTest.class.getClassLoader().getResourceAsStream("hikari.properties")) {
            properties.load(resourceAsStream);

            // 创建 Hikari 连接池的配置对象
            HikariConfig config = new HikariConfig(properties);

            // 通过配置对象来创建连接池
            try (HikariDataSource hikariDataSource = new HikariDataSource(config)) {
                // 获取连接
                try (Connection connection = hikariDataSource.getConnection()) {
                    System.out.println("CRUD");
                }
            }

        } catch (IOException | SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
